"""
插件框架使用示例
演示如何使用插件管理器加载和运行插件
"""

import os
import sys
import logging

# 添加项目根目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from plugin_framework.plugin_manager import PluginManager
from plugin_framework.api_context import APIContext


def setup_logging():
    """设置日志"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )


def main():
    """主函数"""
    setup_logging()
    
    # 创建插件管理器
    plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
    api_context = APIContext("MainApp")
    
    # 设置一些全局配置
    api_context.set_config('app_name', 'Plugin Framework Demo')
    api_context.set_config('version', '1.0.0')
    
    manager = PluginManager(plugin_dir, api_context)
    
    print("=== 插件框架演示 ===")
    
    # 1. 扫描插件
    print("\n1. 扫描插件...")
    discovered = manager.scan(auto_load=True)
    print(f"发现插件: {discovered}")
    
    # 2. 获取已加载的插件
    print("\n2. 已加载的插件:")
    loaded_plugins = manager.get_all()
    for name, plugin in loaded_plugins.items():
        print(f"  - {plugin}")
    
    # 3. 运行插件
    print("\n3. 运行插件...")
    hello_plugin = manager.get('hello_plugin')
    if hello_plugin:
        # 运行几次
        for i in range(3):
            result = hello_plugin.run(name=f"User{i+1}")
            print(f"  运行结果: {result}")
        
        # 获取调用次数
        count = hello_plugin.get_call_count()
        print(f"  插件被调用了 {count} 次")
    
    # 4. 测试服务注册
    print("\n4. 测试服务注册...")
    service = api_context.get_service('hello_service')
    if service:
        result = service.run(name="ServiceUser")
        print(f"  通过服务调用: {result}")
    
    # 5. 测试钩子
    print("\n5. 测试钩子...")
    def plugin_loaded_handler(plugin_name):
        print(f"  钩子触发: 插件 {plugin_name} 已加载")
    
    hook_hub = api_context.get_hook_hub()
    hook_hub.on('plugin_loaded', plugin_loaded_handler)
    
    # 重新加载插件来测试钩子
    print("  重新加载插件...")
    manager.reload('hello_plugin')
    
    # 6. 卸载插件
    print("\n6. 卸载插件...")
    success = manager.unload('hello_plugin')
    print(f"  卸载结果: {'成功' if success else '失败'}")
    
    print("\n=== 演示结束 ===")


if __name__ == "__main__":
    main()